package com.vf.cloud.api.biz.controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.vf.cloud.api.biz.service.IThumbnail;
import com.vf.cloud.common.datasource.annotation.Tx;
import com.vf.cloud.common.domain.Dict;
import com.vf.cloud.common.domain.DictItem;
import com.vf.cloud.common.domain.Project;
import com.vf.cloud.common.repository.base.Thumbnail;
import com.vf.cloud.common.util.R;
import com.vf.cloud.common.util.UuidUtil;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("/project")
public class ProjectController {

	@Autowired
	private IThumbnail thumbnailImpl;

	@GetMapping(value = { "/list" }, produces = "application/json; charset=utf-8")
	public R<Page<Project>> findList(
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "status", required = false, defaultValue = "") String status,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {

		String sqlExceptSelect = " FROM " + Project.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keywords + "%' ) ";
		}
		sqlExceptSelect += "  ORDER BY   O.UPDATE_TIME asc ";
		Page<Project> pages = Project.dao.paginate(cur, limit, "select * ", sqlExceptSelect);
		return R.ok(pages);
	}

	@Tx
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<Project> save(MultipartFile file, Project model) {
		try {
			Thumbnail thumbnailEntity = null;
			if (file != null) {
				thumbnailEntity = new Thumbnail();
				thumbnailEntity.setSize(file.getSize());
				thumbnailEntity.setName(model.getName());
				thumbnailEntity.setContentType(file.getContentType());
				thumbnailEntity.setUploadDate(new Date(System.currentTimeMillis()));
				thumbnailEntity.setContent(new Binary(file.getBytes()));
			}

			if (StrKit.isBlank(model.getName())) {
				return R.failed("名称不可以为空！");
			}

			if (StrKit.isBlank(model.getExeFilePath())) {
				return R.failed("可执行文件路径必填！");
			}

			File f = new File(model.getExeFilePath());
			if (!f.exists()) {
				return R.failed("无效可执行文件路径！");
			}

			if (StrKit.notBlank(model.getId())) {
				if (model.update()) {
					if (thumbnailEntity != null) {
						try {
							thumbnailEntity.setId(model.getId());
							thumbnailImpl.save(thumbnailEntity);
						} catch (Exception e) {
						}
					}
					return R.ok(model);
				} else {
					return R.failed("更新失败！");
				}
			} else {
				model.setId(UuidUtil.getUUID());
				if (model.save()) {
					if (thumbnailEntity != null) {
						try {
							thumbnailEntity.setId(model.getId());
							thumbnailImpl.save(thumbnailEntity);
						} catch (Exception e) {
						}
					}
					return R.ok(model);
				} else {
					return R.failed("保存失败！");
				}
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@Tx
	@RequestMapping(value = "/deleteById", method = RequestMethod.GET)
	public R<String> deleteById(@RequestParam(name = "id") String id) throws Exception {
		try {
			Project role = Project.dao.findById(id);
			if (role == null)
				return R.failed("数据不存在，刷新后尝试!");
			if (role.delete()) {
				try {
					thumbnailImpl.deleteById(role.getId());
				} catch (Exception e) {
				}
				return R.ok();
			}

			return R.failed("失败！");
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@RequestMapping(value = "/getById", method = RequestMethod.GET)
	public R<Project> getById(@RequestParam(name = "id") String id) throws Exception {
		try {
			Project sever = Project.dao.findById(id);
			if (sever == null)
				return R.failed("数据不存在，刷新后尝试!");
			return R.ok(sever);
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@GetMapping(value = "/thumbnail/{id}", produces = { MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE })
	@ResponseBody
	public byte[] image(@PathVariable String id) {
		byte[] data = null;
		Thumbnail thumbnail = thumbnailImpl.findById(id);
		if (thumbnail != null) {
			data = thumbnail.getContent().getData();
		}
		return data;
	}

	@RequestMapping(value = "/getTypes", method = RequestMethod.GET)
	public R<Dict> getTypes() throws Exception {
		try {
			
			Dict dict = Dict.dao.findByCode("Industry");
			if (dict != null) {
				List<DictItem> items = DictItem.dao.find("select * from " + DictItem.TABLE_NAME + " where DICT_ID=? order by sort asc ",dict.getId());
				dict.setItems(items);
				return R.ok(dict);
			}else {
				return R.failed();
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

}
